package com.itheima.springbootwebtlias.aspect;

import com.itheima.springbootwebtlias.commons.CurrentHolder;
import com.itheima.springbootwebtlias.mapper.OperateLogMapper;
import com.itheima.springbootwebtlias.pojo.OperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component

public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* com.itheima.springbootwebtlias.service.*Service.*(..)) && @annotation(com.itheima.springbootwebtlias.anno.LogOperation)")
    public Object recordOperationLog(ProceedingJoinPoint pjp) throws Throwable {

        long start = System.currentTimeMillis();

        Object proceed = pjp.proceed();

        long end = System.currentTimeMillis();




        //1.定义操作日志对象，收集操作日志信息。
        OperateLog operateLog = new OperateLog();

        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        operateLog.setReturnValue(proceed + "");//返回结果
        operateLog.setCostTime(end - start);//执行耗时


        //通过连接点对象ProceedingJoinPoint，获取目标方法信息
        operateLog.setClassName(pjp.getTarget().getClass().getName());//获取目标方法所属的类名称
        operateLog.setMethodName(pjp.getSignature().getName());//获取目标方法名称
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//获取目标方法的参数

        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());

        //2.调用操作日志的持久层接口，添加日志信息到操作日志表中

        operateLogMapper.insert(operateLog);

        return proceed;
    }


}
